﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Net;
using System;
public class Downloader : MonoBehaviour
{
    public UnityWebRequest[] Requests { get; private set; }
    public AsyncOperation CurrentAsyncOperation { get; private set; }

    //当下载开始
    public event Action<Downloader> OnStartAll;
    //当单个文件开始下载
    public event Action<UnityWebRequest> OnStartOne;
    //当下载完一个
    public event Action<UnityWebRequest> OnFinishOne;
    //当下载完所有
    public event Action<Downloader> OnFinishAll;

    private void Start()
    {
        //开始下载
        StartCoroutine("StartDownLoad");
    }

    //下载   (我们这里没有考虑因为网络异常导致中途某个文件下载失败的问题)
    private IEnumerator StartDownLoad()
    {
        OnStartAll?.Invoke(this);

        for (int i = 0; i < Requests.Length; i++)
        {
            if (Requests[i] == null) continue;
            OnStartOne?.Invoke(Requests[i]);
            var asycOp = Requests[i].SendWebRequest();
            CurrentAsyncOperation = asycOp;
            yield return asycOp;
            // if (!string.IsNullOrEmpty(Requests[i].error))
            // {
            //可以在这里得到请求是否出错
            // }
            OnFinishOne?.Invoke(Requests[i]);
        }

        OnFinishAll?.Invoke(this);
    }

    //通过这个静态方法来使用
    public static Downloader Download(params string[] urls)
    {
        Downloader downloader = new GameObject("Downloader").AddComponent<Downloader>();
        //构造请求对象
        UnityWebRequest[] requests = new UnityWebRequest[urls.Length];
        for (int i = 0; i < urls.Length; i++)
        {
            if (string.IsNullOrWhiteSpace(urls[i])) continue;//跳过空url
            requests[i] = UnityWebRequest.Get(urls[i]);
        }
        downloader.Requests = requests;
        return downloader;
    }
}